import axios from 'axios';
import config from '@/config';
import postMessage from './postMessage';

function downloadImage(props: {
    "url": string
    "auth_key": string
    "aes_key": string
    "file_name": ""
}) {
    return new Promise((resolve, reject) => {
        axios({
            method: 'post',
            url: config.robotHost,
            data: {
                "app_key": config.app_key,
                "app_secret": config.app_secret,
                "path": "/cloud/cdn_wx_download",
                "data": {
                    guid: config.guid,
                    ...props
                }
            }
        }).then(response => {
            console.log('Image downloaded successfully:', response.data);
            resolve(response.data.data.url);
        }).catch(error => {
            reject(`Error downloading image: ${error.message}`);
        });
    });
}

// 盒子打印图片
async function postImgToPrint(props: Parameters<typeof downloadImage>[0], conversation_id: string) {
    const url = await downloadImage(props)

    console.log('Image URL:', url);

    return axios({
        method: 'post',
        url: config.bearHost + '/print/user/sendBoxPrintImage',
        data: {
            "boxDeviceId": "lk20ge09412577",
            "boxDeviceKey": "gGmsqYCDV8vYc5hE",
            "imageUrl": url
        }
    }).then(response => {
        console.log('Image sent to print successfully:', response.data);
        if (response.data.data.code === -1) {
            toMessage(JSON.stringify(response.data));
        }
    }).catch(error => {
        console.error('Error sending image to print:', error.message);
        toMessage()
    });

    function toMessage(str = '') {
        postMessage({
            "conversation_id": conversation_id,
            "content": `打印失败，url: ${url} \n 错误信息: ${str}`
        })
    }
}

export default postImgToPrint;
